import msgBoxVue from './Message.vue';

// 定义插件对象
const Message = {};
// vue的install方法，用于定义vue插件
Message.install = function (Vue, options) {
    const MessageBoxInstance = Vue.extend(msgBoxVue);
    let currentMsg;
    const initInstance = () => {
        // 实例化vue实例
        currentMsg = new MessageBoxInstance();
        let msgBoxEl = currentMsg.$mount().$el;
        document.body.appendChild(msgBoxEl);
    };

    // 在Vue的原型上添加实例方法，以全局调用
    Vue.prototype.$ucMessage = {
        show (options) {
            if (!currentMsg) {
                initInstance();
            }
            if (typeof options === 'string') {
                currentMsg.content = options;
            } else if (typeof options === 'object') {
                console.log(options)
                Object.assign(currentMsg, options);
            }
            return currentMsg.show().then(val => {
                    console.log(currentMsg)
                    currentMsg = null;
                    return Promise.resolve(val);
                }).catch(err => {
                    currentMsg = null;
                    return Promise.reject(err);
                });
        },
        close(){
            if (currentMsg){
                currentMsg.close()
            }
        }
    };
}

export default Message;